package com.bi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bi.entity.DataComponentField;
import com.bi.mapper.DataComponentFieldMapper;
import com.bi.service.DataComponentFieldService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据组件字段服务实现类
 * 
 * @author BI Platform Team
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DataComponentFieldServiceImpl extends ServiceImpl<DataComponentFieldMapper, DataComponentField> implements DataComponentFieldService {

    @Override
    public List<DataComponentField> getFieldsByComponentId(Long componentId) {
        return baseMapper.selectByComponentId(componentId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveFields(Long componentId, List<DataComponentField> fields) {
        try {
            if (fields == null || fields.isEmpty()) {
                return true;
            }

            // 设置组件ID和时间
            for (int i = 0; i < fields.size(); i++) {
                DataComponentField field = fields.get(i);
                field.setComponentId(componentId);
                field.setCreateTime(LocalDateTime.now());
                field.setUpdateTime(LocalDateTime.now());
                
                // 如果没有设置排序顺序，使用索引
                if (field.getSortOrder() == null) {
                    field.setSortOrder(i + 1);
                }
                
                // 设置默认值
                if (field.getVisible() == null) {
                    field.setVisible(true);
                }
                if (field.getSearchable() == null) {
                    field.setSearchable(false);
                }
                if (field.getSortable() == null) {
                    field.setSortable(false);
                }
                if (field.getFilterable() == null) {
                    field.setFilterable(false);
                }
                if (field.getAlign() == null) {
                    field.setAlign(DataComponentField.AlignType.LEFT);
                }
            }

            // 批量插入
            int insertCount = baseMapper.batchInsert(fields);
            
            log.info("批量保存字段配置成功: componentId={}, count={}", componentId, insertCount);
            return insertCount > 0;

        } catch (Exception e) {
            log.error("批量保存字段配置失败: componentId={}, error={}", componentId, e.getMessage(), e);
            throw new RuntimeException("保存字段配置失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteFieldsByComponentId(Long componentId) {
        try {
            int deleteCount = baseMapper.deleteByComponentId(componentId);
            log.info("删除组件字段配置成功: componentId={}, count={}", componentId, deleteCount);
            return true;
        } catch (Exception e) {
            log.error("删除组件字段配置失败: componentId={}, error={}", componentId, e.getMessage(), e);
            throw new RuntimeException("删除字段配置失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updateFieldSort(Long componentId, Long fieldId, Integer sortOrder) {
        try {
            int updateCount = baseMapper.updateSortOrder(componentId, fieldId, sortOrder);
            log.info("更新字段排序成功: componentId={}, fieldId={}, sortOrder={}", componentId, fieldId, sortOrder);
            return updateCount > 0;
        } catch (Exception e) {
            log.error("更新字段排序失败: componentId={}, fieldId={}, error={}", componentId, fieldId, e.getMessage());
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copyFields(Long sourceComponentId, Long targetComponentId) {
        try {
            // 获取源组件的字段配置
            List<DataComponentField> sourceFields = baseMapper.selectByComponentId(sourceComponentId);
            
            if (sourceFields.isEmpty()) {
                log.info("源组件无字段配置，跳过复制: sourceComponentId={}", sourceComponentId);
                return true;
            }

            // 创建新的字段配置
            List<DataComponentField> newFields = new ArrayList<>();
            for (DataComponentField sourceField : sourceFields) {
                DataComponentField newField = new DataComponentField();
                newField.setComponentId(targetComponentId);
                newField.setFieldName(sourceField.getFieldName());
                newField.setDisplayName(sourceField.getDisplayName());
                newField.setFieldType(sourceField.getFieldType());
                newField.setFormatRule(sourceField.getFormatRule());
                newField.setWidth(sourceField.getWidth());
                newField.setVisible(sourceField.getVisible());
                newField.setSearchable(sourceField.getSearchable());
                newField.setSortable(sourceField.getSortable());
                newField.setFilterable(sourceField.getFilterable());
                newField.setAlign(sourceField.getAlign());
                newField.setRenderer(sourceField.getRenderer());
                newField.setValidationRule(sourceField.getValidationRule());
                newField.setDefaultValue(sourceField.getDefaultValue());
                newField.setDescription(sourceField.getDescription());
                newField.setSortOrder(sourceField.getSortOrder());
                newField.setCreateTime(LocalDateTime.now());
                newField.setUpdateTime(LocalDateTime.now());
                
                newFields.add(newField);
            }

            // 批量保存
            return saveFields(targetComponentId, newFields);

        } catch (Exception e) {
            log.error("复制字段配置失败: sourceComponentId={}, targetComponentId={}, error={}", 
                     sourceComponentId, targetComponentId, e.getMessage(), e);
            throw new RuntimeException("复制字段配置失败: " + e.getMessage());
        }
    }

    @Override
    public List<DataComponentField> generateFieldsFromDataSource(Long componentId, String dataSourceConfig) {
        List<DataComponentField> fields = new ArrayList<>();
        
        try {
            // 这里是简化实现，实际应该解析数据源配置，自动生成字段
            // 可以从数据库表结构、ES映射、API响应结构等自动生成字段配置
            
            // 示例：生成一些默认字段
            String[] defaultFields = {"id", "name", "createTime", "status"};
            String[] defaultDisplayNames = {"ID", "名称", "创建时间", "状态"};
            DataComponentField.FieldType[] defaultTypes = {
                DataComponentField.FieldType.NUMBER,
                DataComponentField.FieldType.STRING,
                DataComponentField.FieldType.DATETIME,
                DataComponentField.FieldType.ENUM
            };

            for (int i = 0; i < defaultFields.length; i++) {
                DataComponentField field = new DataComponentField();
                field.setComponentId(componentId);
                field.setFieldName(defaultFields[i]);
                field.setDisplayName(defaultDisplayNames[i]);
                field.setFieldType(defaultTypes[i]);
                field.setVisible(true);
                field.setSearchable(i > 0); // ID字段不可搜索
                field.setSortable(true);
                field.setFilterable(i > 1); // 前两个字段不可过滤
                field.setAlign(i == 0 ? DataComponentField.AlignType.CENTER : DataComponentField.AlignType.LEFT);
                field.setSortOrder(i + 1);
                field.setCreateTime(LocalDateTime.now());
                field.setUpdateTime(LocalDateTime.now());
                
                fields.add(field);
            }

            log.info("自动生成字段配置成功: componentId={}, count={}", componentId, fields.size());

        } catch (Exception e) {
            log.error("自动生成字段配置失败: componentId={}, error={}", componentId, e.getMessage(), e);
        }

        return fields;
    }
}